#include "app.h"
int MCU_VERSION = 0;

#define HC32TESTLED Pin06	  // PB7
#define HC32TESTLEDPORT PortB // PB7
#define BED_TYPE 66		  // 66:1024||67:160


// 新增一个全局变量，用于标记是否正在发送分钟数据
// static bool is_sending_minute_data = false;
// void System_SoftReset(void);
/*
0x00：WIFI 处于配网状态
0x01：WIFI 未连接到路由器，未连接到服务器
0x02：WIFI 连接到路由器，未连接到服务器
0x03：WIFI 连接到路由器，并连接到服务器，未鉴权成功
0x04：WIFI 连接到路由器，并连接到服务器，鉴权成功
*/
// 一长两短        配网中
// 慢闪          无网络
int time_stamp = 0;
int netokflag = 1;

int nonettimes = 0;

/// @brief flash存储数据
uint8_t out_bed;
uint8_t out_bed2;
uint8_t out_bed3;

// uint8_t outarr[3] = {0};
extern ExtY_nczallcode_T nczallcode_Ytemp;
static int riskreport = 0;


// static int macsend = 1;

uint8_t get_net_count = 0;

void set_net_count(uint8_t count)
{
	get_net_count = count;
}

void System_SoftReset(void)
{
	
	__set_FAULTMASK(1);
  NVIC_SystemReset();  // 直接触发软复位，无需额外操作
}


void app_task(void *pvParameters)
{
		DDL_DelayMS(2000);
		protocol_handle.get_4G_IMEI();
		vTaskDelay(2000);
		
		protocol_handle.send_mcu_version(1,0,3);
		vTaskDelay(300);

	while (1)
	{
		
			if (get_otaflag() == 1)
			{
				set_otaflag(0);
				unsigned char start_ota[50] = {0x55, 0xAA, 0x81, 0x10, 0x00, 0x85, 0x00, 0x00, 0x00, 0x00,0x00,0xFE};
				USART_SendData_DMA(start_ota, 12); // start ota
				vTaskDelay(1000);
				System_SoftReset();
			}
#if 1
				// 风险上报
					switch ((int)nczallcode_Ytemp.merged_alarm) {
									
									case 0:
										riskreport = 0;
										break;
									case 10:
									case 14:
									case 13:
										if (riskreport == 0) {
											riskreport = 1;
											//test1111111111111111111111111111
											static uint8_t riskrebuff[1024];
											
											// memset(riskrebuff, 0, sizeof(riskrebuff));
											
											for (int i = 0; i < 1024; i++)
											{
												// 除系数防止溢出,1024/4.160/6   ADC处理后这边置1即可
												// int div_ce = 1;
												riskrebuff[i] = (uint8_t)frameDatatemp[i];
											}
					
											protocol_handle.package_riskreportingdata(riskrebuff);
											//test1111111111111111111111111111

											
										}
										break;
									default:
										break;
					 }


					if ((int)nczallcode_Ytemp.sosflag == 0x1 && nczallcode_Y.rate != -1)
					 {
						protocol_handle.send_SoScoordinateArr();
						
					 }
							
#endif	

#if 1
			if ((adc_handle.send_2sdataflag == 1) && (netokflag == 1))
			{
				adc_handle.send_2sdataflag = 0;
			
//(int breathrate,int strokeRisk,int inBedtime,int stateInBbed,int bodyMovementData);
#if 1
				int bodydata[24];
				for (int i = 0; i < 24; i++)
				{
					bodydata[i] = (int)nczallcode_Ytemp.bodyMovementData[i];
				}
#endif
				if (nczallcode_Ytemp.rate != 0xffffffff){
	
				// protocol_handle.send_mcu_version(1,2,3);
					protocol_handle.package_realsosdata((int)nczallcode_Ytemp.rate, (int)nczallcode_Ytemp.strokerisk, (int)nczallcode_Ytemp.inBedtime,
					(int)nczallcode_Ytemp.stateInBbed, bodydata,(uint8_t)nczallcode_Ytemp.sosflag,(uint8_t)nczallcode_Ytemp.current_threshold,(uint8_t)nczallcode_Ytemp.on_bed_duration_minutes,(uint8_t)nczallcode_Ytemp.sitting_alarm_duration_minutes,(uint8_t)nczallcode_Ytemp.falling_alarm_duration_minutes,(uint8_t)nczallcode_Ytemp.merged_alarm);

				}
													 
			}else if (netokflag != 1)
			{
				
				protocol_handle.get_net_status();
				switch (get_net_led())
				{
					
				case 0x00: // config net
				Set_LED_State(LED_STATUS_NETWORK);
					netokflag = 0;
					break;
				
				case 0x02:
					Set_LED_State(LED_STATUS_OFF);
					netokflag = 0;
					break;

				case 0x01: // config net
					Set_LED_State(LED_STATUS_QUICK_BLINK);
						netokflag = 0;
						break;	

				
				case 0x04:
					netokflag = 1;
					Set_LED_State(LED_STATUS_ON);
					break;
					
				default:
					netokflag = 0;
					if (gpio_handle.start_netconfig_flag != 1)
					{
						Set_LED_State(LED_STATUS_OFF);
						netokflag = 1;
					}
					break;
				}
			}
#endif
			if ((adc_handle.send_1mdataflag == 1) && (netokflag == 1))
			{
				//  USART_SendData_DMA("8",1);
				adc_handle.send_1mdataflag = 0;
#if 1
				static uint8_t martix[1024];
				// memset(martix, 0, sizeof(martix));
				// uint32_t statesleep[48];
				int statesleepsend[48];
				for (int i = 0; i < 1024; i++)
				{
					martix[i] =(uint8_t)frameDatatemp[i];


					// 除系数防止溢出,1024/4.160/6
					// int div_ce = 1;
					// if((uint8_t)(frameDatatemp[i] / div_ce)<5){
					// 	martix[i] = 0;
					// }else if((uint8_t)(frameDatatemp[i] / div_ce)>=255){
					// 	martix[i] = 255;
					// }else{
					// martix[i] = ((uint8_t)(frameDatatemp[i] / div_ce));
					// }
				}
#if 1
				for (int i = 0; i < 48; i++)
				{
					statesleepsend[i] = nczallcode_Ytemp.statesleep[i];
				}
#endif
#endif

				if (nczallcode_Ytemp.rateMin != -1)
				{
					 protocol_handle.package_oneminsdata(nczallcode_Ytemp.rateMin, nczallcode_Ytemp.strokeriskMin, statesleepsend, nczallcode_Ytemp.timt, nczallcode_Ytemp.meansn, martix, BED_TYPE);
				// protocol_handle.send_mcu_version(0x01,0x01,0x02);
				}
			}


		

			// //获取堆栈调用状况
			// UBaseType_t uxHighWaterMark;
            //     uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL);

            //       char stack_info[100];
            //     sprintf(stack_info, "Stack Usage: %u bytes\r\n", uxHighWaterMark);
                
            //     // 先发送堆栈信息
            //     USART_SendData_DMA((uint8_t*)stack_info, strlen(stack_info));
	
			vTaskDelay(120);
		
	}
}
//

void app_start(void)
{

	// 创建队列
    xADCDataQueue = xQueueCreate(10, sizeof(ADCDataMessage));
    
    // 创建互斥锁（保护 frameDatatemp）
    xFrameDataMutex = xSemaphoreCreateMutex();
	
	// 创建接收数据队列
    xRxQueue = xQueueCreate(RX_QUEUE_LENGTH, sizeof(RxDataMsg));
    configASSERT(xRxQueue != NULL);

    // 创建缓冲区互斥锁
    xRxBufferMutex = xSemaphoreCreateMutex();
    configASSERT(xRxBufferMutex != NULL);

	// xTaskCreate((TaskFunction_t)gpio_timer,
    // (const char *)"gpio_timer",
    // (uint16_t)1000,
    // (void *)NULL,
    // (UBaseType_t)3,
    // NULL);


	xTaskCreate((TaskFunction_t )adc_task,     
	(const char *)"adc_task",   
	(uint16_t)4000, //3000
	(void *)NULL,
	(UBaseType_t    )6,
	NULL); 	

	xTaskCreate(
		nczallcode_task, 
		"nczallcode_task", 
		25000,//21000 25000---170KB
		 NULL,
		  6, 
		  NULL);

	xTaskCreate((TaskFunction_t)app_task,
				(const char *)"app_task",
				(uint16_t)6000,
				(void *)NULL,
				(UBaseType_t)4,
				NULL);

	// xTaskCreate((TaskFunction_t)send_second1024_task,
	// 			(const char *)"send_second1024_task",
	// 			(uint16_t)1000,
	// 			(void *)NULL,
	// 			(UBaseType_t)4,
	// 			NULL);			

	xTaskCreate(
					uart_process_task,
					"uart_proc",
					1000,
					NULL,
					5, // 优先级高于 app_task
					NULL
				);	
	xTaskCreate(
					get_passbackflash_task,
					"get_passback_flash",
					3000,
					NULL,
					3, // 优先级高于 app_task
					NULL
				);		
}
